package com.quanjiaolian.tools;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

/**
 * 工具类：将数据封装成json格式返回给客户端
 * @author Herson_Li
 *
 */
public class ResponseToJson {
	
	/**
	 * 声明Log4j变量
	 */
	public static ResourceBundle resourceBundle = null;
	static Logger logger = Logger.getLogger(ResponseToJson.class.getName());
	
	/**
	 * 以JSON格式输出
	 * @param response
	 */
	public static void responseOutWithJson(HttpServletResponse response,
			Object responseObject) {
		//将实体对象转换为JSON Object转换
		JSONObject responseJSONObject = JSONObject.fromObject(responseObject);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(responseJSONObject.toString());
			logger.info("返回的json数据为：");
			logger.info(responseJSONObject.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	/**
	 * 将List转换成json
	 * @param response
	 * @param responseList
	 */
	public static void responseListOutWithJson(HttpServletResponse response,
			List<Object> responseList){
		//将List转换成JSONArray
		JSONArray ja = JSONArray.fromObject(responseList);
		Map<String,Object> ma = new HashMap<String,Object>();
		ma.put("result", ja);
		JSONObject responseJSONObject = JSONObject.fromObject(ma);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(responseJSONObject.toString());
			logger.info("返回的JSONArray数据为：");
			logger.info(ja.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	public static void main(String[] args) {
		List<Object> list = new ArrayList<Object>();
		
		for(int i=0;i<5;i++){
			Map<String,Object> ma = new HashMap<String,Object>();
			ma.put("id","123");
			ma.put("name","张三");
			ma.put("age","12");
			ma.put("sex","1");
			ma.put("address","北京市朝阳区");
			ma.put("msisdn","18912345678");
			list.add(ma);
		}
		
		JSONArray responseJSONObject = JSONArray.fromObject(list);
		System.out.println(responseJSONObject.toString());
	}
}
